/**
 * 个人所得税导入
 */
import { connect } from 'umi';
import React, { useCallback, useEffect, useMemo } from 'react';
import { Button, Form, Spin, Table, message, Modal, Tooltip, Icon, Typography } from 'antd';
import { formatMessage } from 'umi';
import classNames from 'classnames';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import { SearchInput } from '@/components/UserForm';
import OrganizationSelect from '@/components/OrganizationSelect';
import { withRoutePage } from '@/utils/enhanceUtils';
import { isSuccess } from '@/utils/request';
import AuthComponent from '@/utils/auth/AuthComponent';
import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import { premiumBaseService } from '@/services/salaryManage/salaryCalculate';

import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import ExcelUploader from '@/pages/SalaryManage/SalaryCalculate/ImportExcel/ExcelUploader';
import SalaryConfigTipPage from '@/pages/SalaryManage/components/SalaryConfigTipPage';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import { goToPremiumBaseEdit, goToPremiumBaseLog } from '@/pages/SalaryManage/utils/pageNavigateUtil';
import { useHandleRefreshMessage } from '@/pages/SalaryManage/utils/tabMessageUtil';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import styles from '@/pages/SalaryManage/SalaryCalculate/ImportExcel/index.less';

import ImportExcelRouter from '../component/ImportExcelRouter';
import ImportExcelMenuFilter from '../component/ImportExcelMenuFilter';

const { getStatusSocial } = premiumBaseService;

const SearchForm = Form.create()(({ form, searchModel, onChange, organizationCode }) => {
    const { getFieldDecorator } = form;

    return (
        <Form layout="inline">
            <Form.Item label="员工" className={salaryStyle.flex} style={{ width: '280px' }}>
                {getFieldDecorator('employeeCode', {
                    ...(searchModel?.employeeCode ? { initialValue: searchModel.employeeCode } : {})
                })(
                    <SearchInput
                        params={{
                            organizationCode
                        }}
                        getData={async params => {
                            if (!params.organizationCode) {
                                return [];
                            }
                            const employeeResponse = await queryEmployeeList({
                                organizationCode: params.organizationCode
                            });
                            return isSuccess(employeeResponse) ? employeeResponse.data || [] : [];
                        }}
                        selectProps={{
                            placeholder: '请输入员工姓名',
                            allowClear: true
                        }}
                        fieldsName={{
                            value: 'employeeCode',
                            title: 'name'
                        }}
                        onChange={onChange}
                        style={{ width: '220px' }}
                    />
                )}
            </Form.Item>
        </Form>
    );
});

const SalaryPayrollTax = ({
    columns,
    dataSource,
    rowKey,
    pagination,
    loading,
    pageLoading,
    showImportDialog,
    uploadAction,
    showTemplateButton,
    user,
    dispatchType,
    dispatch,
    uploadExtraParams,
    searchModel,
    selectOrganizationCode,
    organizationResponse
}) => {
    const {
        initType,
        tablePageChangeType,
        searchType,
        showImportDialogType,
        completeType,
        cancelType,
        deleteType,
        mergeSearchModelType
    } = dispatchType;

    const [initStatus, setInitStatus] = React.useState(0);

    // 分页按钮
    const tablePageChange = ({ current, pageSize }) => {
        dispatch({
            type: tablePageChangeType,
            payload: { current, pageSize }
        });
    };

    // 导入按钮
    const importExcel = () => {
        dispatch({
            type: showImportDialogType,
            payload: true
        });
    };

    // 表单column
    const operateAction = {
        onEdit(record) {
            goToPremiumBaseEdit(record);
        },
        onDelete(record) {
            dispatch({
                type: deleteType,
                payload: record.id,
                currentRecord: record
            });
        }
    };

    const initFn = async () => {
        if (selectOrganizationCode) {
            try {
                const [statusResponse] = await Promise.all([getStatusSocial(selectOrganizationCode)]);
                if (isSuccess(statusResponse)) {
                    setInitStatus(statusResponse.data);
                } else {
                    message.error(statusResponse.msg);
                }
            } catch (e) {
                console.log(e);
            }
        }
    };

    useEffect(() => {
        initFn();
    }, [selectOrganizationCode]);

    const completeFn = () => {
        dispatch({
            type: completeType,
            payload: {
                organizationCode: selectOrganizationCode
            },
            callback() {
                initFn();
            }
        });
    };

    // 完成初始化按钮
    const completeInitFn = () => {
        if (dataSource && dataSource.length === 0) {
            Modal.confirm({
                title: '当前未导入任何初始化数据，是否确认初始化完成？',
                onOk() {
                    completeFn();
                }
            });
        } else {
            completeFn();
        }
    };

    // 取消初始化按钮
    const cancelInitFn = () => {
        dispatch({
            type: cancelType,
            payload: {
                organizationCode: selectOrganizationCode
            },
            callback() {
                initFn();
            }
        });
    };

    useEffect(() => {
        if (selectOrganizationCode) {
            dispatch({ type: initType, payload: { organizationCode: selectOrganizationCode, needReset: true } });
        }
    }, [selectOrganizationCode]);

    // 员工切换搜索
    const onChange = useCallback(employeeCode => {
        dispatch({
            type: mergeSearchModelType,
            payload: { employeeCode }
        });
        dispatch({
            type: searchType
        });
    }, []);

    const searchNode = useMemo(
        () => <SearchForm searchModel={searchModel} onChange={onChange} organizationCode={selectOrganizationCode} />,
        [searchModel, user, onChange, selectOrganizationCode]
    );

    const handleOrganizationChange = useCallback(
        value => {
            if (selectOrganizationCode !== value) {
                dispatch({
                    type: 'importExcelModel/setMultiStore',
                    payload: {
                        selectOrganizationCode: value,
                        countryNameCode: null
                    }
                });
            }
        },
        [selectOrganizationCode]
    );

    useHandleRefreshMessage();

    return (
        <PageHeaderWrapper type="success">
            <BaseSettingProvider organizationCode={selectOrganizationCode}>
                <ImportExcelMenuFilter>
                    <ImportExcelRouter
                        type="salaryExcelImport"
                        extraButton={
                            <div className={salaryStyle.flex}>
                                <div className={classNames([salaryStyle.flex, salaryStyle.mr12])}>
                                    <OrganizationSelect
                                        isStrictly
                                        isNeedPermission
                                        style={{ width: 220 }}
                                        onChange={handleOrganizationChange}
                                        value={selectOrganizationCode}
                                        allowClear={false}
                                        dropdownMatchSelectWidth
                                        treeDataFromProp
                                        treeDataList={organizationResponse}
                                    />
                                </div>
                                <div>
                                    <Button onClick={() => goToPremiumBaseLog(selectOrganizationCode)}>操作日志</Button>
                                </div>
                            </div>
                        }
                    >
                        <SalaryConfigTipPage organizationCode={selectOrganizationCode}>
                            <Spin spinning={pageLoading}>
                                <div className={styles.salaryExcelBox}>
                                    <TwoColHead
                                        left={searchNode}
                                        right={
                                            <>
                                                <Tooltip
                                                    title="在下次险金基数变更前，以【初始月薪】和【初始月绩效】做为计算基础"
                                                    overlayStyle={{ maxWidth: 260 }}
                                                >
                                                    <span style={{ cursor: 'pointer' }}>
                                                        <Typography.Text type="warning">取值说明</Typography.Text>
                                                        <Icon
                                                            type="question-circle"
                                                            style={{ marginLeft: '5px', opacity: 0.65 }}
                                                        />
                                                    </span>
                                                </Tooltip>
                                                <AuthComponent code="finance:salary:computation:import:socialinit:import">
                                                    <Button onClick={importExcel}>
                                                        {/* 导入 */ formatMessage({ id: 'importExcel.import' })}
                                                    </Button>
                                                </AuthComponent>

                                                {initStatus === 1 ? (
                                                    <Button type="primary" onClick={cancelInitFn}>
                                                        {/* 初始化取消 */ formatMessage({
                                                            id: 'importExcel.initCancel'
                                                        })}
                                                    </Button>
                                                ) : (
                                                    <Button
                                                        type="primary"
                                                        onClick={completeInitFn}
                                                        disabled={initStatus === 2}
                                                    >
                                                        {/* 初始化完成 */ formatMessage({
                                                            id: 'importExcel.initComplete'
                                                        })}
                                                    </Button>
                                                )}
                                            </>
                                        }
                                    />
                                    <div className={styles.tableBox}>
                                        <Table
                                            layout="fixed"
                                            bordered
                                            columns={
                                                typeof columns === 'function'
                                                    ? columns(pagination, operateAction, initStatus)
                                                    : columns
                                            }
                                            rowKey={rowKey}
                                            dataSource={dataSource}
                                            pagination={false}
                                            loading={loading.effects[searchType]}
                                            scroll={{ x: 'max-content' }}
                                        />
                                    </div>
                                    <Pagination {...pagination} onChange={tablePageChange} />
                                </div>

                                <ExcelUploader
                                    showImportDialog={showImportDialog}
                                    uploadAction={uploadAction}
                                    dispatchType={dispatchType}
                                    dispatch={dispatch}
                                    showTemplateButton={showTemplateButton}
                                    user={user}
                                    // extra={uploadExtra}
                                    extraParams={uploadExtraParams}
                                />
                            </Spin>
                        </SalaryConfigTipPage>
                    </ImportExcelRouter>
                </ImportExcelMenuFilter>
            </BaseSettingProvider>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ premiumBaseModel, loading, user, importExcelModel }) => ({
        ...premiumBaseModel,
        selectOrganizationCode: importExcelModel.selectOrganizationCode,
        organizationResponse: importExcelModel.organizationResponse,
        loading,
        dispatchType: {
            initType: 'premiumBaseModel/init',
            searchType: 'premiumBaseModel/search',
            deleteType: 'premiumBaseModel/deletePremiumBase',
            completeType: 'premiumBaseModel/completePremiumBase',
            cancelType: 'premiumBaseModel/cancelPremiumBase',
            tablePageChangeType: 'premiumBaseModel/tablePageChange',
            showImportDialogType: 'premiumBaseModel/showImportDialog',
            downloadTemplateType: 'premiumBaseModel/downloadTemplate',
            setMultiStoreType: 'premiumBaseModel/setMultiStore',
            mergeSearchModelType: 'premiumBaseModel/mergeSearchModel'
        },
        showTemplateButton: true,
        templateUrl: '/api/finance/salary/v1/template/excels/socialInitTemplate.xlsx',
        uploadAction: `/api/finance/salary/v1/social/init/import/${importExcelModel.selectOrganizationCode}`,
        user
    }))(SalaryPayrollTax)
);
